import React, { Component } from 'react'
import './Item.css'
import context from '../../context'
export default class Item extends Component {
  state = {
    info: '',
    autofocus: '',
  }
  static contextType = context
  render() {
    const { info, autofocus } = this.state
    const { todo } = this.props
    const { id, todoName, isDone } = todo
    const { Del, UpdataOneIsDone, id: EditId, EditToggle, EditTodoName } = this.context
    return (
      <li>
        {id !== EditId ?
          <label>
            <input type="checkbox" checked={isDone} onChange={() => { UpdataOneIsDone(id) }} />
            <span>{todoName}</span>
          </label> :
          <input
            type='text'
            value={info}
            id={id}
            autoFocus={autofocus}
            // 2.这里是动态渲染文本框里边的值
            onChange={(e) => { this.setState({ info: e.target.value }) }}
            // 3.键盘监听事件,最后操作App.js中的私有数据
            onKeyUp={(e) => {
              if (e.keyCode !== 13 || !e.target.value) return
              EditTodoName(id, info)
            }}
          ></input>
        }
        <button
          className="btn btn-danger"
          onClick={() => {
            Del(id)
          }}
        >删除</button>
        <button
          className='btn'
          style={{ backgroundColor: 'skyblue', color: '#fff', border: 'none', marginRight: 10 }}
          onClick={() => {
            EditToggle(id)
            // 1.当点击文本框的时候，显示任务名称
            this.setState({
              info: todoName,
              autofocus: 'autofocus'
            })
          }}
        >
          {id !== EditId ? '编辑' : '取消'}
        </button>
      </li>
    )
  }
}
